﻿using Core.Web.Admin.Blazor.Models;
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Core.Web.Admin.Blazor.Utils
{
    public class CurrentUserContext
    {
        private readonly AuthenticationStateProvider _authenticationStateProvider;
        public CurrentUserContext(AuthenticationStateProvider authenticationStateProvider)
        {
            _authenticationStateProvider = authenticationStateProvider;
        }
        public  async Task< CurrentUserInfo> GetCurrentUser()
        {
            CurrentUserInfo currentUser = new CurrentUserInfo();
            var authentication = await _authenticationStateProvider.GetAuthenticationStateAsync();
            if (authentication.User.Claims.Count() > 0)
            {
                var roles = authentication.User.Claims.Where(m => m.Type == ClaimTypes.Role).Select(m => m.Value).ToList();
                currentUser.Id = authentication.User.Claims.FirstOrDefault(m => m.Type == ClaimTypes.NameIdentifier)?.Value;
                currentUser.TrueName = authentication.User.Identity.Name;
                currentUser.Role = roles;
            }
            return currentUser;
        }
    }
}
